package io

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"log"
	"os"
)

func WriteFile() {
	file, err := os.Create("training/testfile.txt")
	if err != nil {
		log.Fatal("创建文件失败...")
		return
	}
	defer file.Close()
	file.WriteString("这是个测试文本")
	log.Println("写入内容完毕")
}

func ReadFile() {
	f, err := os.Open("training/myfile.txt")
	if err != nil {
		log.Fatal("打开文件失败...")
		return
	}
	//关闭文件
	defer f.Close()

	fileInfo, _ := f.Stat()
	bs := make([]byte, fileInfo.Size())
	_, er := f.Read(bs)
	if er != nil {
		fmt.Println(er)
	}

	content := string(bs)
	fmt.Println("文件内容：", content)
}

func ReadByIo() {
	bs, err := ioutil.ReadFile("training/myfile.txt")
	if err != nil {
		log.Println("读取文件错误...")
		return
	}
	str := string(bs)
	fmt.Println("文件内容为：", str)
}

func ExampleWriter() {
	w := bufio.NewWriter(os.Stdout)
	fmt.Fprint(w, "Hello, ")
	fmt.Fprint(w, "world!\n")
	w.Flush() // Don't forget to flush!
	// Output: Hello, world!
}
